package org.qiancizhan.API;

import java.util.ArrayList;
import java.lang.System;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import org.qiancizhan.Model.DTO.AIConversationContentDTO;
import org.qiancizhan.Utils.ConfigUtil;
import org.qiancizhan.Utils.RandomIDGenerateUtil;
import org.slf4j.LoggerFactory;

public class ALiYun_TongYiAi {
    public CompletableFuture<List<AIConversationContentDTO>> sendMessage(List<AIConversationContentDTO> originalMessages) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ((Logger) LoggerFactory.getLogger("com.aliyun")).setLevel(Level.ERROR);
                ((Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME)).setLevel(Level.ERROR);
            } catch (Exception e) {
                System.out.println("初始化失败");
            }

            Generation gen = new Generation();
            List<Message> messageList = new ArrayList<>();
            for (AIConversationContentDTO message : originalMessages) {
                messageList.add(Message.builder()
                        .role(message.getMessage_type())
                        .content(message.getMessage_content())
                        .build());
            }
            GenerationParam param = GenerationParam.builder()
                    .apiKey(ConfigUtil.get("aliyun.tongYi.apiKey"))
                    .model(ConfigUtil.get("aliyun.tongYi.model"))
                    .messages(messageList)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();
            try {
                GenerationResult result = gen.call(param);
                List<AIConversationContentDTO> resultMessages = new ArrayList<>(originalMessages);
                resultMessages.add(new AIConversationContentDTO(
                        RandomIDGenerateUtil.generateRandomID(),
                        Role.ASSISTANT.getValue(),
                        result.getOutput().getChoices().get(0).getMessage().getContent()
                ));
                return resultMessages;
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                e.printStackTrace();
                return new ArrayList<>(originalMessages);
            }
        });
    }
}
